package leetcode.code0508;

import java.util.HashMap;
import java.util.Map;

import leetcode.IDebug;
import leetcode.helper.tree.TreeNode;

public class Solution implements IDebug {

	Map<Integer, Integer> times;
	int max;
	int count;

	public int[] findFrequentTreeSum(TreeNode root) {
		max = 0;
		count = 0;
		times = new HashMap<>();
		this.f(root);
		int[] ans = new int[count];
		int p = 0;
		for (Map.Entry<Integer, Integer> entry : times.entrySet()) {
			int sum = entry.getKey(), time = entry.getValue();
			if (time == max) {
				ans[p++] = sum;
			}
		}
		return ans;
	}

	private int f(TreeNode root) {
		if (root == null) {
			return 0;
		}
		int sum = root.val;
		sum += this.f(root.left);
		sum += this.f(root.right);
		int time = times.getOrDefault(sum, 0) + 1;
		times.put(sum, time);
		if (time > max) {
			max = time;
			count = 1;
		} else if (time == max) {
			count++;
		}
		return sum;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
